package com.nic.view.net;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;

import com.nic.view.R;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2018/6/5.
 */

public class NetProgressDialog {
    private Activity activity;
    private Map<Activity, AlertDialog> map = new HashMap<>();

    public NetProgressDialog(Activity activity) {
        this.activity = activity;
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_aq_progress, null);
        AlertDialog dialog = new AlertDialog.Builder(activity, R.style.dialog_no_bg).setView(view).create();
        dialog.setCancelable(false);
        map.put(activity, dialog);
    }

    public void setCancelable(boolean c) {
        if (!activity.isFinishing()) {
            if (map.containsKey(activity)) {
                AlertDialog dialog = map.get(activity);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(c);
            }
        }
    }

    public void show() {
        if (!activity.isFinishing()) {
            if (map.containsKey(activity)) {
                AlertDialog dialog = map.get(activity);
                if (dialog != null && !dialog.isShowing() && !activity.isFinishing()) {
                    dialog.show();
                }
            }
        }

    }

    public boolean isShowing() {
        if (!activity.isFinishing()) {
            if (map.containsKey(activity)) {
                AlertDialog dialog = map.get(activity);
                if (dialog != null && dialog.isShowing()) {
                    return true;
                }
            }
        }
        return false;
    }


    public void dismiss() {
        if (!map.isEmpty()) {
            for (Map.Entry<Activity, AlertDialog> m : map.entrySet()) {
                if (m.getValue().isShowing()) {
                    m.getValue().dismiss();
                }
                if (m.getKey().isFinishing()) {
                    map.remove((m.getKey()));
                }

            }
        }
        if (!activity.isFinishing()) {
            if (map.containsKey(activity)) {
                map.remove(activity);
            }
        }


    }
}
